#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/9/27 9:19
# @Author : 闫峰
# @File    : test_monitor_java_listing_walmart.py
import os
from common.setting import ensure_path_sep
from third_services.allegro.RebatyesAndPromotions.offerdetails import OfferDetails
from third_services.allegro.RebatyesAndPromotions.rebatesAndPromotions import RebatesAndPromotions
from utils.logging_tool.log_control import LogHandler
from utils.mysqlUtils.db_pool import Database
from utils.noticeUtils.dingtalkControl import DingTalkSendMsg
from concurrent.futures import ThreadPoolExecutor, wait, as_completed
from functools import partial

current_path = os.path.abspath(__file__)
current_dir = os.path.dirname(current_path)
path_list = current_path.split("\\")
dis_path = "\\".join(path_list[-2:-1])
info_path = ensure_path_sep(f"\\logs\\info-{dis_path}.log")
error_path = ensure_path_sep(f"\\logs\\\error-{dis_path}.log")
warning_path = ensure_path_sep(f"\\logs\\warning-{dis_path}.log")
if os.path.exists(info_path):
    os.remove(info_path)
if os.path.exists(error_path):
    os.remove(error_path)
if os.path.exists(warning_path):
    os.remove(warning_path)
INFO = LogHandler(info_path, level='info')
ERROR = LogHandler(error_path, level='error')
WARNING = LogHandler(warning_path, level='warning')

net_db = Database(ensure_path_sep("\\testcases\\Intelligent_publishing\\sku_category\\config.yaml"),
                  "znkd_database_prod")
global_str = ""
count = 0

class TestSkuCategory:
    """
    检测 类目映射 增量同步  从java组类目库 同步到 智能刊登库
    """

    def atest_sku_category(self):
        net_db = Database(ensure_path_sep("\\testcases\\Intelligent_publishing\\sku_category\\config.yaml"),
                          "znkd_database_prod")
        api = OfferDetails()
        api1 = RebatesAndPromotions()
        global global_str
        global count
        get_java_count = f"""
        SELECT
	OrderSourceId,ItemId
FROM
	`irobotbox_marketpublish`.`pp_phoenixplan_allegro_queue` 
WHERE
	`CustomerId` = 1
	AND MarketId=67
	AND `StrategyId` =9390 
	AND `Status`='success'
	AND StrategyType=5
	AND Time >= "2023-10-23 00:00:00"
        """
        java_count = net_db.fetch_all_tuple(get_java_count, ())
        for data in java_count:
            res = api1.get_sale_loyalty_promotions_offerid(data[0],data[1])
            # print(res)
            PromotionId = res['promotions'][0]['id']
            offer_count = len(res['promotions'][0]['offerCriteria'])
            offer_count = api1.get_sale_loyalty_promotions_data(data[0],PromotionId)
            offer_count = len(offer_count['offerCriteria'])
            print(f"渠道={data[0]},offer= {data[1]} 参加的活动={PromotionId} offer数{offer_count}")


    def test_run(self):
        t = TestSkuCategory()
        get_source_id_list = """
        SELECT a.OrderSourceId FROM sys_ordersource a 
        LEFT JOIN sys_ordersource_authorization b ON a.CustomerId=b.CustomerId AND a.OrderSourceId=b.OrderSourceId
        WHERE 
        a.OrderSourceType =67
        AND a.IsActive=1 AND a.IsDelete=0 AND b.IsActive=1
        """
        source_id_list = net_db.fetch_all_tuple(get_source_id_list, ())
        source_id_list = list(map(lambda x: x[0], source_id_list))
        # source_id_list = [9058,9059,9062,9046,10190,10205,10206]
        executor = ThreadPoolExecutor(max_workers=8)
        tasks = []
        for i in source_id_list:
            # 使用funools.partial函数创建一个新的函数，将参数绑定到函数中
            new_task = partial(t.atest_sku_category, i)
            # executor.submit(new_task)
            tasks.append(executor.submit(new_task))
        INFO.logger.info(f"任务数{len(tasks)}")

        # 等待所有任务完成
        done, not_done = wait(tasks, return_when='ALL_COMPLETED')
        """
        在这个修改后的代码中，wait 函数会接收一个任务列表，并等待所有的任务完成。
        return_when 参数设置为 'ALL_COMPLETED'，表示当所有的任务都已完成时返回。
        返回的结果是一个包含两个集合的元组，第一个集合 done 包含已经完成的任务，第二个集合 not_done 包含还未完成的任务。
        然后，你可以遍历 done 集合来处理已经完成的任务的结果。
        注意这里使用 future.result() 来获取任务的结果，如果任务抛出了异常，那么 result 将是异常的实例，你可以进行处理。
        """
        # 处理已完成的任务
        # for future in done:
        #     try:
        #         result = future.result()
        #         print(f"参数是 {result[0]}, 结果是 {result[1]}")
        #     except Exception as e:
        #         print(f"任务执行出现异常，参数是 {result[0]}")
        #         raise

        # 关闭线程池
        executor.shutdown()
        print(count)
        DingTalkSendMsg(DingTalk='allegro_monitor').send_success(text=global_str,
                                                                 title='Allegro平台java端在线listing（差异大于1000）同步监控服务',
                                                                 phone_list=[18576757471, 18118758151])



if __name__ == '__main__':
    TestSkuCategory().atest_sku_category()